package com.cheng.servlet;

import com.cheng.exception.ExceptionView;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

//springmvc处理异常，必须实现接口HandlerExceptionResolver接口
//springmvc提供了实现类
/*
* 1、ExceptionHandlerExceptionResolver： 主要提供了@ExceptionHandler注解，并通过该注解处理异常
* 2、ResponseStatusExceptionResolver    自定义异常显示页面 @ResponseStatus
 * */
@Controller
@RequestMapping("tryCatch")
public class TryCatch {
    @RequestMapping("tryCatche")
    public String tryCatch(){
        //servlet出现异常
        //模拟一场异常
        //java处理异常try {
            System.out.println(1/0);//报该异常 ArithmeticException
        //}catch ()
        return "city";
    }


    @RequestMapping("tryCatche2")
    public String tryCatc2h(){
        //servlet出现异常
        //模拟一场异常
        //java处理异常try {
        int[] a=new int[]{1};
        System.out.println(a[2]);//数组越界
        //}catch ()
        return "city";
    }


//仅处理该类的异常
    @ExceptionHandler({ArithmeticException.class,ArrayIndexOutOfBoundsException.class}/*那个捕获类路劲（本身或者基类，本身短）最短哪个捕获*/)//可指定捕获什么异常
    //springmvc处理异常需要单独一个类  该类会捕获其他方法出现的异常
    public ModelAndView handlerArithmeticException(Exception e){
        System.out.println(e);
        ModelAndView mv=new ModelAndView("error");
        mv.addObject("er",e);
        return mv;
    }



    //测试自定义异常,有相应的springmvc处理类的异常捕获则不会来到这里
    @RequestMapping("testExceptionView")
    public String testExceptionView(@RequestParam("i") int i) throws ExceptionView {
        if (i==3){
            throw new ExceptionView();//符合条件时抛出自定义异常
        }
        return "city";
    }


    //方法中使用自定义异常注解
    @RequestMapping("testExceptionView1")
    public String testExceptionView1(@RequestParam("i") int i) throws ExceptionView {
        if (i==3){
            return "redirect:ExceptionView";
        }
        return "city";
    }

    @RequestMapping("ExceptionView")
    @ResponseStatus(value = HttpStatus.FORBIDDEN,reason = "数组越界")//资源找不到
    public String ExceptionView(){
        return "error";
    }


}
